package mutilthread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description: 模拟实现一个固定线程数目的简单线程池
 * User: Li_yizYa
 * Date: 2025—04—01
 * Time: 19:34
 */

class MyThreadPool {
    // 任务队列（阻塞队列）
    private final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    // 此处 n 表示要创建几个线程
    public MyThreadPool(int n) {
        // 先创建出 n 个线程
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                // 循环的从队列中来取任务，
                while (true) {
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }
    }
    // 添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
}
public class Demo20 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println("执行任务" + id + ", " + Thread.currentThread().getName());
            });
        }
    }
}
